package com.liziba.unsafe;

import sun.misc.Unsafe;

/**
 * <p>
 *      操作数组示例
 * </p>
 *
 * @Author: Liziba
 * @Date: 2021/5/23 13:33
 */
public class OperateArrayExample {


    /**
     *  1、public native int arrayBaseOffset(Class<?> var1); 获取数组第一个元素的偏移地址
     *  2、public native int arrayIndexScale(Class<?> var1); 获取数组中元素的增量地址
     *  3、public Object getObject(Object var1, int var2); 通过对象和地址偏移量获取元素
     */
    public static void operateArrayUseUnsafe() {
        // 测试数组
        String[] exampleArray = new String [] {"李" , "子", "捌"};

        Unsafe unsafe = UnsafeFactory.getUnsafe();
        // 获取数组的基本偏移量
        int baseOffset = unsafe.arrayBaseOffset(String[].class);
        System.out.println("String[] base offset is : " + baseOffset);

        // 获取数组中元素的增量地址
        int scale = unsafe.arrayIndexScale(String[].class);
        System.out.println("String[] index scale is : " + scale);

        // 获取数组中第n个元素 i = (baseOffset + (scale * n-1))
        System.out.println("third element is :" + unsafe.getObject(exampleArray, baseOffset + (scale * 2)));

        // 修改数组中第n个元素 i = (baseOffset + (scale * n-1))
        unsafe.putObject(exampleArray, baseOffset + scale * 2, "柒");
        System.out.println("third element is :" + unsafe.getObject(exampleArray, baseOffset + (scale * 2)));
    }

    public static void main(String[] args) {
        OperateArrayExample.operateArrayUseUnsafe();
    }

}
